var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');

var app = getApp();

Page({
  data: {
    // 小区信息
    currentCommunity: "白城市",
    
    // 服务项目
    serviceItems: ["家政保洁", "家电维修", "管道疏通", "宠物护理", "搬家服务"],
    selectedService: "家政保洁",
    
    // 需求信息
    demandInfo: "",
    imageUrl: "",
    
    // 地址信息
    addressList: ["白城市洮北区"],
    selectedAddress: "白城市洮北区",
    doorNumber: "瑞光南街69-8-12号",
    phone: "",
    // 时间选择
    timeOptions: ["及时上门", "今日内", "明日", "预约时间"],
    selectedTime: "及时上门",
    
    // 费用信息
    serviceFee: 0,
    couponList: ["请选择", "满50减10", "满100减30", "新用户立减15"],
    selectedCoupon: "请选择",
    fee: 0,
    
    // 发布按钮状态
    canPublish: true
  },
  
  onLoad() {
    // 初始化计算费用
    this.calculateTotal();
  },
  
  // 返回上一页
  onBackTap() {
    wx.navigateBack({
      delta: 1
    });
  },
  
  // 服务项目选择
  onServiceChange(e) {
    const index = e.detail.value;
    this.setData({
      selectedService: this.data.serviceItems[index]
    }, () => {
      this.checkPublishable();
    });
  },
  
  // 需求信息输入
  onDemandInput(e) {
    this.setData({
      demandInfo: e.detail.value
    }, () => {
      this.checkPublishable();
    });
  },
  
  // 选择图片
  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '上传中...'
        });
        
        // 调用后台服务上传图片
        wx.uploadFile({
          url: api.PublishUpload,
          filePath: tempFilePaths[0],
          name: 'file',
          success: (uploadRes) => {
            const data = JSON.parse(uploadRes.data);
            if (data.errno === 0) {
              this.setData({
                imageUrl: data.data.url
              });
              wx.hideLoading();
              wx.showToast({
                title: '上传成功',
                icon: 'success'
              });
            } else {
              wx.hideLoading();
              wx.showToast({
                title: data.errmsg || '上传失败',
                icon: 'none'
              });
            }
          },
          fail: () => {
            wx.hideLoading();
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        });
      }
    });
  },
  
  // 地址选择
  onAddressChange(e) {
    const index = e.detail.value;
    this.setData({
      selectedAddress: this.data.addressList[index]
    }, () => {
      this.checkPublishable();
    });
  },
  
  // 门牌号输入
  onDoorNumberInput(e) {
    this.setData({
      doorNumber: e.detail.value
    });
  },
  
  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    }, () => {
      this.checkPublishable();
    });
  },

  // 时间选择
  onTimeChange(e) {
    this.setData({
      selectedTime: e.detail.value
    });
  },
  
  // 费用输入
  onFeeInput(e) {
    const fee = parseFloat(e.detail.value) || 0;
    this.setData({
      serviceFee: fee
    }, () => {
      this.calculateTotal();
      this.checkPublishable();
    });
  },
  
  // 优惠券选择
  onCouponChange(e) {
    const index = e.detail.value;
    this.setData({
      selectedCoupon: this.data.couponList[index]
    }, () => {
      this.calculateTotal();
    });
  },
  
  // 计算总费用
  calculateTotal() {
    let fee = this.data.serviceFee;
    
    // 根据优惠券计算折扣
    if (this.data.selectedCoupon === "满50减10" && fee >= 50) {
      fee -= 10;
    } else if (this.data.selectedCoupon === "满100减30" && fee >= 100) {
      fee -= 30;
    } else if (this.data.selectedCoupon === "新用户立减15") {
      fee -= 15;
    }
    
    // 确保费用不小于0
    fee = Math.max(0, fee);
    
    this.setData({
      fee: fee.toFixed(2)
    });
  },
  
  // 检查是否可以发布
  checkPublishable() {
    const canPublish = 
      this.data.selectedService 
      // && 
      // this.data.demandInfo.trim() && 
      // this.data.selectedAddress && 
      // this.data.serviceFee > 0;
      
    this.setData({
      canPublish
    });
  },
  
  // 处理发布
  handlePublish() {
    console.log("handlePublish start!");
    if (!this.data.canPublish) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }
    // 1. 收集表单数据
    const formData = {
      community: this.data.currentCommunity,
      serviceType: this.data.selectedService,
      demandInfo: this.data.demandInfo,
      images: this.data.imageUrl,
      address: this.data.selectedAddress,
      doorNumber: this.data.doorNumber,
      serviceTime: this.data.selectedTime,
      serviceFee: this.data.serviceFee,
      coupon: this.data.selectedCoupon,
      fee: this.data.fee,
      phone: this.data.phone
    };
    console.log("handlePublish 1!");
    // 2. 显示加载中
    wx.showLoading({
      title: '发布中...',
      mask: true
    });
    console.log("handlePublish 2!");
    util.request(api.PublishCreate, formData, 'POST').then(res => {
      wx.hideLoading();
      if (res.errno === 0) {
        wx.showToast({
          title: '发布成功',
          icon: 'success'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: res.errmsg || '发布失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.log("handlePublish 3!"+JSON.stringify(err));
      wx.hideLoading();
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    });
    // 3. 模拟接口请求
    // setTimeout(() => {
    //   // 实际项目中替换为wx.request调用后端接口
    //   console.log("发布的数据：", formData);
      
    //   // 隐藏加载
    //   wx.hideLoading();
      
    //   // 显示成功提示
    //   wx.showToast({
    //     title: '发布成功',
    //     icon: 'success',
    //     duration: 2000,
    //     mask: true
    //   });
      
    //   // 延迟返回上一页
    //   setTimeout(() => {
    //     wx.navigateBack({
    //       delta: 1
    //     });
    //   }, 2000);
    // }, 1500);
  }
});
